import socket
import threading

# 创建一个 TCP 套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服务器地址和端口
server_address = ("192.168.8.149", 8765)
# 连接到服务器
client_socket.connect(server_address)
print(f"已连接到服务器: {server_address}")

def receive_messages():
    while True:
        try:
            # 接收服务器消息
            message = client_socket.recv(1024).decode('utf-8')
            if not message:
                break
            print(f"{message}")
        except Exception as e:
            print(f"接收消息时出错: {e}")
            break

# 启动一个线程来接收服务器消息
receive_thread = threading.Thread(target=receive_messages)
receive_thread.start()

while True:
    try:
        # 从客户端终端获取输入
        message = input("客户端: ")
        if message.lower() == 'quit':
            break
        # 发送消息到服务器
        client_socket.sendall(message.encode('utf-8'))
    except Exception as e:
        print(f"发送消息时出错: {e}")
        break

# 关闭连接
client_socket.close()
